package com.bub.pay.core.manager.merchant.impl;

import com.bub.pay.core.dao.SysUserDao;
import com.bub.pay.core.dao.SysUserRoleDao;
import com.bub.pay.core.entity.domain.SysRole;
import com.bub.pay.core.entity.dto.merchant.MerchantUserDTO;
import com.bub.pay.core.entity.dto.merchant.NewBuiltMerchantEmployeeDTO;
import com.bub.pay.core.entity.dto.merchant.ResetPasswordDTO;
import com.bub.pay.core.entity.vo.merchant.MerchantEmployeeVo;
import com.bub.pay.core.manager.client.ClientManager;
import com.bub.pay.core.manager.user.UserCommonManager;
import com.bub.pay.core.util.SignUtil;
import com.bub.pay.framework.common.base.Cause;
import com.bub.pay.framework.common.base.Module;
import com.bub.pay.core.enums.UserTypeEnum;
import com.bub.pay.framework.common.entity.model.SessionModel;
import com.bub.pay.framework.common.exception.GlobalException;
import com.bub.pay.core.entity.domain.SysUser;
import com.bub.pay.core.entity.domain.SysUserRole;
import com.bub.pay.core.entity.dto.merchant.MerUserDTO;
import com.bub.pay.core.base.BaseManagerAbstract;
import com.bub.pay.core.manager.merchant.MerUserManager;
import com.bub.pay.core.entity.vo.merchant.MerchantUserVo;
import com.bub.pay.framework.common.template.EmailTemplate;
import com.bub.pay.framework.common.util.ContextHolder;
import com.bub.pay.framework.common.util.EncryptionUtil;
import com.bub.pay.framework.common.util.GoogleAuthenticator;
import com.bub.pay.framework.redis.RedisClient;
import com.bub.pay.framework.redis.model.EmailModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: wing
 * @Date: 2019/4/10 16:56
 */
@Service
@Transactional
public class MerUserManagerImpl extends BaseManagerAbstract<SysUser, SysUserDao> implements MerUserManager {

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Resource
    private UserCommonManager userCommonManager;

    @Resource
    private RedisClient redisClient;

    @Resource
    private ClientManager clientManager;

    private ExecutorService executorService = Executors.newFixedThreadPool(20);

//    @Override
//    public int addMerchantEmployee(MerchantUserVo vo) {
//        Date now = new Date();
//        SysUser user = new SysUser();
//        BeanUtils.copyProperties(vo, user);
//        user.setId(null);
//        user.setUserType(UserTypeEnum.merchant.getType());
//        user.setCreateDate(now);
//        user.setUpdateDate(now);
//        user.setCreateId(vo.getId());
//        user.setUpdateId(user.getCreateId());
//
//        int count = sysUserDao.insertSelective(user);
//        if (count < 1) {
//            throw new GlobalException(Module.merchant, Cause.unknown);
//        }
//        SysUserRole userRole = new SysUserRole();
//        userRole.setCreateDate(now);
//        userRole.setCreateId(vo.getExtendId());
//        userRole.setRoleId(vo.getRoleId());
//        userRole.setUpdateDate(now);
//        userRole.setUserId(user.getId());
//        userRole.setUpdateId(vo.getExtendId());
//        count = sysUserRoleDao.insertSelective(userRole);
//        return count;
//    }

    @Override
    public int newBuiltMerchantEmployee(NewBuiltMerchantEmployeeDTO dto) {
        if (dto == null) {
            throw new IllegalArgumentException("请求不能为空");
        }
        SessionModel sessionModel = ContextHolder.currentUserInfo();
        Long operatorId = sessionModel.getUserId();
        SysUser sysUser = new SysUser();
        Date now = new Date();
        sysUser.setUserType(UserTypeEnum.merchant.getType());
        sysUser.setCreateDate(now);
        sysUser.setUpdateDate(now);
        sysUser.setCreateId(operatorId);
        sysUser.setUpdateId(operatorId);
        sysUser.setUserName(dto.getUsername());
        sysUser.setNickName(dto.getNickname());
        sysUser.setEmail(dto.getEmail());
        sysUser.setState(dto.getStatus());
        final String googleSecret = resetGoogleSecretKey();
        final String password = resetPWD();
        sysUser.setPassword(EncryptionUtil.encode().encode(password));
        sysUser.setGoogleSecret(googleSecret);
        int count = sysUserDao.insertSelective(sysUser);
        if (count < 1) {
            throw new GlobalException(Module.merchant, Cause.unknown);
        }
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userName", sysUser.getUserName());
        SysUser newUser = sysUserDao.selectOneByExample(example);
        SysUserRole userRole = new SysUserRole();
        userRole.setCreateDate(now);
        userRole.setCreateId(operatorId);
        userRole.setUserId(newUser.getId());
        userRole.setRoleId(dto.getRoleId());
        userRole.setUpdateDate(now);
        userRole.setUpdateId(operatorId);
        count = sysUserRoleDao.insertSelective(userRole);
        if (count < 1) {
            throw new GlobalException(Module.merchant, Cause.unknown);
        }
//        //新建成功  发送邮件
//        executorService.submit(() -> {
//            Map<String, String> data = new HashMap<>();
//            data.put("username", sysUser.getUserName());
//            data.put("password", password);
//            data.put("googleSecret", googleSecret);
//            EmailModel emailModel = new EmailModel();
//            emailModel.setAddress(sysUser.getEmail());
//            emailModel.setData(data);
//            emailModel.setTemplateId(EmailTemplate.TEMPLATE_NEW_BUILT_MERCHANT_EMPLOYEE);
//            System.out.println(emailModel);
//            clientManager.sendEmail(emailModel);
//            return null;
//        });
        //新建成功  发送邮件
        Map<String,String> data = new ConcurrentHashMap<>();
        data.put("username", sysUser.getUserName());
        data.put("password", password);
        data.put("googleSecret", googleSecret);
        sendEmail(sysUser.getEmail(),data,EmailTemplate.TEMPLATE_NEW_BUILT_MERCHANT_EMPLOYEE);
        return count;
    }

    private void sendEmail(final String address , final Map<String,String> data , final String template){
        executorService.submit(() -> {
            EmailModel emailModel = new EmailModel();
            emailModel.setAddress(address);
            emailModel.setData(data);
            emailModel.setTemplateId(template);
            System.out.println(emailModel);
            clientManager.sendEmail(emailModel);
            return null;
        });
    }

    @Override
    public List<MerUserDTO> selectMerUserPage(SysUser user) {

        return sysUserDao.selectMerUserPage(user);
    }

    @Override
    public int updateMerUser(SysUser user, SysUserRole userRole) {
        int count = sysUserDao.updateByPrimaryKeySelective(user);
        if (count > 0) {
            Example example = new Example(SysUserRole.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userRole.getUserId());

            count = sysUserRoleDao.updateByExampleSelective(userRole, example);
        }
        return count;
    }

    @Override
    public List<MerchantUserDTO> selectMerchantUser(MerchantEmployeeVo merchantEmployee) {
        if (merchantEmployee == null) {
            throw new IllegalArgumentException("请求不能为空");
        }
        merchantEmployee.setNickName("%" + merchantEmployee.getNickName() + "%");
        return sysUserDao.selectMerchantEmployee(merchantEmployee);
    }

    @Override
    public int updateMerchantEmployeeStatus(MerchantEmployeeVo merchantEmployeeVo) {
        if (merchantEmployeeVo == null) {
            throw new IllegalArgumentException("请求不能为空");
        }
        if (merchantEmployeeVo.getId() <= 0) {
            throw new IllegalArgumentException("请传入正确的id");
        }
        if (merchantEmployeeVo.getStatus() != 1 && merchantEmployeeVo.getStatus() != 2) {
            return 0;
        }

        return sysUserDao.updateMerchantEmployeeStatus(merchantEmployeeVo);
    }

    @Override
    public int deleteMerchantEmployee(MerchantEmployeeVo merchantEmployeeVo) {
        if (merchantEmployeeVo == null) {
            throw new IllegalArgumentException("请求不能为空");
        }
        if (merchantEmployeeVo.getId() <= 0) {
            throw new IllegalArgumentException("请输入正确的id");
        }
        int count = 0;
        Example example = new Example(SysUserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",merchantEmployeeVo.getId());
        Example userExample = new Example(SysUser.class);
        Example.Criteria userExampleCriteria = userExample.createCriteria();
        userExampleCriteria.andEqualTo("id",merchantEmployeeVo.getId());

        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setDelFlag(true);
        SysUser sysUser = new SysUser();
        sysUser.setDelFlag(true);

        count += sysUserDao.updateByExampleSelective(sysUser,userExample);
        count += sysUserRoleDao.updateByExampleSelective(sysUserRole,example);
        return count;
    }

    @Override
    public int updateMerchantEmployee(MerchantEmployeeVo merchantEmployeeVo) {
        int successRows = 0;
        SysUser sysUser = new SysUser();
        SysUserRole userRole = new SysUserRole();
        SessionModel sessionModel = ContextHolder.currentUserInfo();
        if (merchantEmployeeVo == null) {
            throw new IllegalArgumentException("请求不能为空");
        }
        if (merchantEmployeeVo.getId() <= 0)
            throw new IllegalArgumentException("请输入正确的id");
        if (merchantEmployeeVo.getNickName() != null && "".equals(merchantEmployeeVo.getNickName())) {
            throw new IllegalArgumentException("姓名不能为空");
        }
        if (merchantEmployeeVo.getEmail() != null && "".equals(merchantEmployeeVo.getEmail())) {
            throw new IllegalArgumentException("邮箱不能为空");
        }
        if (merchantEmployeeVo.getRoleId() != null) {
//            Integer roleId = sysUserDao.selectRoleIdByRoleName(merchantEmployeeVo.getRoleName());
//            successRows += sysUserDao.updateEmployeeRole(roleId, merchantEmployeeVo.getId());
            Example example = new Example(SysUserRole.class);
            Example.Criteria criteria = example.createCriteria();
            userRole.setUserId(merchantEmployeeVo.getId());
            criteria.andEqualTo("userId",userRole.getUserId());
            userRole.setRoleId(merchantEmployeeVo.getRoleId());
            Date date = new Date();
            userRole.setUpdateDate(date);
            userRole.setUpdateId(sessionModel.getUserId());
            List<SysUserRole> userRole1 = sysUserRoleDao.selectByExample(example);
            if(userRole1 == null || userRole1.size() == 0){
                userRole.setCreateId(sessionModel.getUserId());
                userRole.setCreateDate(date);
                successRows += sysUserRoleDao.insertSelective(userRole);
            }else {
                successRows += sysUserRoleDao.updateByExampleSelective(userRole,example);
            }
        }
        if (merchantEmployeeVo.getStatus() != null && merchantEmployeeVo.getStatus() != 1 && merchantEmployeeVo.getStatus() != 2)
            throw new IllegalArgumentException("员工状态不正确");

        sysUser.setId(merchantEmployeeVo.getId());
        sysUser.setNickName(merchantEmployeeVo.getNickName());
        sysUser.setEmail(merchantEmployeeVo.getEmail());
        sysUser.setState(merchantEmployeeVo.getStatus());
        successRows += sysUserDao.updateByPrimaryKeySelective(sysUser);
        return successRows;
    }

    @Override
    public int resetMerchantPassword(ResetPasswordDTO resetPasswordDTO) {
        if (resetPasswordDTO == null) {
            throw new IllegalArgumentException("请求不能为空");
        }
        SysUser user = sysUserDao.selectByPrimaryKey(resetPasswordDTO.getUserId());
        if (user == null) {
            throw new IllegalArgumentException("用户id不存在");
        }
        //发送邮件需要的参数
        String address = user.getEmail();
        String template = "";
        Map<String,String> data = new ConcurrentHashMap<>();
        data.put("username",user.getUserName());

        SessionModel sessionModel = ContextHolder.currentUserInfo();
        Long userId = sessionModel.getUserId();
        SysUser sysUser = new SysUser();
        String password = resetPWD();
        String googleSecret = resetGoogleSecretKey();


        String googleSecret1 = sessionModel.getGoogleSecret();
        long googleCode = Long.parseLong(resetPasswordDTO.getGoogleCode());
        if(!GoogleAuthenticator.check_code(googleSecret1, googleCode,System.currentTimeMillis())){
            throw new IllegalArgumentException("谷歌验证码错误");
        }
        if (resetPasswordDTO.getPasswordType() == 1) {//重置登录密码
            sysUser.setPassword(EncryptionUtil.encode().encode(password.toLowerCase()));
            template = EmailTemplate.TEMPLATE_RESET_MERCHANT_LOGIN_PASSWORD;
            data.put("password",password);
        } else if (resetPasswordDTO.getPasswordType() == 2) {//重置谷歌密钥
            sysUser.setGoogleSecret(googleSecret);
            template = EmailTemplate.TEMPLATE_RESET_MERCHANT_GOOGLE_SECRET;
            data.put("googleSecret",googleSecret);
        } else {
            throw new IllegalArgumentException("错误的密码类型");
        }
        sysUser.setId(resetPasswordDTO.getUserId());
        sysUser.setUpdateDate(new Date());
        sysUser.setUpdateId(userId);
        int i = sysUserDao.updateByPrimaryKeySelective(sysUser);
        if(i < 1 ){
            throw new RuntimeException("重置失败");
        }
        //修改成功  发送邮件通知
        sendEmail(address,data,template);
        return i;
    }

    private String resetPWD() {
        String newPWD = null;
        try {
            newPWD = SignUtil.sign("" + System.currentTimeMillis(), SignUtil.SIGN_WITH_MD5);
        } catch (Exception e) {
            throw new IllegalArgumentException("密码初始化失败");
        }
        return newPWD.substring(0, 16);
    }

    private String resetGoogleSecretKey() {
        return GoogleAuthenticator.generateSecretKey();
    }


}
